import asyncio
from pathlib import Path

from uploader.douyin_uploader.main import DouYinVideo
from uploader.ks_uploader.main import KSVideo
from uploader.tencent_uploader.main import TencentVideo
from uploader.xiaohongshu_uploader.main import XiaoHongShuVideo


from db.sqlite import SQLiteDB
import json
from datetime import timedelta
from datetime import datetime
def upload(job_id):
    if not job_id:
        print('请传入任务id')
    with SQLiteDB() as db:
        results = db.query("SELECT * FROM job WHERE id = ?", (job_id,))
        if not results:
            print('任务不存在')
        job = results[0]
        if not job:
            print('任务不存在')
        account = json.loads(job['account'])
        file = json.loads(job['file'])
        title = job['title']
        topic = json.loads(job['topic'])
        publish = job['publish']

        cookie = account['cookie']
        type = account['type']
        path = file['path']
        # 拼接base
        BASE_DIR = Path(__file__).resolve().parent.parent
        filepath = Path(BASE_DIR / "files" / path)
        cookiepath = Path(BASE_DIR / "cookies" / cookie)
        type = int(type)
        publish = datetime.strptime(publish, "%Y-%m-%d %H:%M:%S")
        try:
            match type:
                case 1: # 小红书
                    app = XiaoHongShuVideo(title, filepath, topic, publish, cookiepath)
                    asyncio.run(app.main(), debug=False)
                case 2: # 视频号
                    app = TencentVideo(title, str(filepath), topic, publish, cookiepath)
                    asyncio.run(app.main(), debug=False)
                case 3: # 抖音
                    app = DouYinVideo(title, str(filepath), topic, publish, cookiepath)
                    asyncio.run(app.main(), debug=False)
                case 4: # 快手
                    app = KSVideo(title, str(filepath), topic, publish, cookiepath)
                    asyncio.run(app.main(), debug=False)
        except Exception as e:
            print(e)
